package com.iwop.moto.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.foxinmy.weixin4j.util.StringUtil;
import com.iwop.moto.comm.ErrCode;
import com.iwop.moto.controller.BaseController;
import com.iwop.moto.model.ResultModel;
import com.iwop.moto.model.SuperRecordModel;
import com.iwop.moto.utils.chat.ChatUtil;
import com.iwop.moto.utils.chat.api.*;
import com.iwop.moto.utils.chat.comm.ClientContext;
import com.iwop.moto.utils.chat.comm.EasemobRestAPIFactory;
import com.iwop.moto.utils.chat.comm.body.AudioMessageBody;
import com.iwop.moto.utils.chat.comm.body.ImgMessageBody;
import com.iwop.moto.utils.chat.comm.body.MessageBody;
import com.iwop.moto.utils.chat.comm.body.TextMessageBody;
import com.iwop.moto.utils.chat.comm.wrapper.ResponseWrapper;
import com.iwop.moto.utils.http.HttpUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.security.auth.Subject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * F_GOODS
 * @author  Created by liuwb on 2016-07-15.
 */
@Controller
public class EasemobController extends BaseController {

    public EasemobRestAPIFactory factory = ClientContext.getInstance().init(ClientContext.INIT_FROM_PROPERTIES).getAPIFactory();
    public IMUserAPI user = (IMUserAPI)factory.newInstance(EasemobRestAPIFactory.USER_CLASS);
    public ChatMessageAPI chat = (ChatMessageAPI)factory.newInstance(EasemobRestAPIFactory.MESSAGE_CLASS);
    public SendMessageAPI esm = (SendMessageAPI)factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
    public FileAPI file = (FileAPI)factory.newInstance(EasemobRestAPIFactory.FILE_CLASS);
    public SendMessageAPI message = (SendMessageAPI)factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
    public ChatGroupAPI chatgroup = (ChatGroupAPI)factory.newInstance(EasemobRestAPIFactory.CHATGROUP_CLASS);
    public ChatRoomAPI chatroom = (ChatRoomAPI)factory.newInstance(EasemobRestAPIFactory.CHATROOM_CLASS);

    /**
     * 功能:环信 添加用户
     * 参数 username
     * 参数 pwd
     * 参数 nickname
     * @return
     */
    @RequestMapping(value = "/api/easemob/adduser", method = { RequestMethod.POST } )
    @ResponseBody
    public ResultModel apiEasemobAddUser(){
        SuperRecordModel SRModel = this.getSRModel();
        try {
            ResponseWrapper rw  =  (ResponseWrapper) ChatUtil.addChatUser(SRModel.getString("username"),
                    SRModel.getString("pwd"), SRModel.getString("nickname"));
            if(rw.getResponseStatus()==200){
                return getSucceed(ErrCode.SUCCEED);
            } else {
                return getErr(ErrCode.ERROR_SYSTEM+"|"+rw.getResponseStatus());
            }
        }catch (Exception e){
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能: 发送文本消息测试
     */
    @RequestMapping(value = "/api/easemob/send/textmsg", method = { RequestMethod.POST } )
    @ResponseBody
    public ResultModel testSendTextMsg(){
        SuperRecordModel SRModel = this.getSRModel();
        try {
            SendMessageAPI esm = (SendMessageAPI)factory.newInstance(EasemobRestAPIFactory.SEND_MESSAGE_CLASS);
            String fromUser = "15959276686";//发送消息者
            String [] toArr = {"User00001","User00002"};//接收消息者
            MessageBody tmb = new TextMessageBody("users",toArr,fromUser,null,"Hello world");
            ResponseWrapper rw = (ResponseWrapper) esm.sendMessage(tmb);
            if(rw.getResponseStatus()==200){
                return getSucceed(rw);
            } else {
                return getErr(ErrCode.ERROR_SYSTEM+"|"+rw.getResponseStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能: 图片消息测试
     * 说明: 需先上传图片到环信服务器
     *       获取到返回的uuid和share-secret标识
     */
    @RequestMapping(value = "/api/easemob/send/imgmsg", method = { RequestMethod.POST } )
    @ResponseBody
    public ResultModel testSendImgMsg(){
        try {
            FileAPI file = (FileAPI)factory.newInstance(EasemobRestAPIFactory.FILE_CLASS);
            ResponseWrapper fileResponse = (ResponseWrapper) file.uploadFile(new File("D:/WX-QRC.png"));
            String uuid = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("uuid").asText();
            String shareSecret = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("share-secret").asText();
            String uri = ((ObjectNode) fileResponse.getResponseBody()).get("uri").asText();
            String fromUser = "zqb";//发送消息者
            String [] toUsers = {"User00001","User00002","15959276686"};//接收消息者
            MessageBody imgBody = new ImgMessageBody("users",toUsers,fromUser,null,uri+"/"+uuid,"测试图片.png",shareSecret,150l,150l);
            ResponseWrapper rw = (ResponseWrapper) esm.sendMessage(imgBody);
            if(rw.getResponseStatus()==200){
                return getSucceed(rw);
            } else {
                return getErr(ErrCode.ERROR_SYSTEM+"|"+rw.getResponseStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能:环信 - 发送语音消息
     * 说明:需先上传语音文件到环信服务器
     *      获取到返回的uuid和share-secret标识
     */
    @RequestMapping(value = "/api/easemob/send/imgaudio", method = { RequestMethod.POST } )
    @ResponseBody
    public ResultModel testSendImgAudio(){
        try {
            FileAPI file = (FileAPI)factory.newInstance(EasemobRestAPIFactory.FILE_CLASS);
            ResponseWrapper fileResponse = (ResponseWrapper) file.uploadFile(new File("d:/合成语音.wav"));
            String uuid = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("uuid").asText();
            String shareSecret = ((ObjectNode) fileResponse.getResponseBody()).get("entities").get(0).get("share-secret").asText();
            String uri = ((ObjectNode) fileResponse.getResponseBody()).get("uri").asText();
            String fromUser = "zqb";//发送消息者
            String [] toUsers = {"User00001","User00002","15959276686"};//接收消息者
            Map<String, String> ext = new HashMap<String, String>();
            ext.put("userId","uuid_test");
            ext.put("orderNo","order_test");
            AudioMessageBody auditMsg = new AudioMessageBody("users",toUsers,fromUser,ext,uri+"/"+uuid,"合成语音.wav",shareSecret,10l);
            ResponseWrapper rw = (ResponseWrapper) esm.sendMessage(auditMsg);
            if(rw.getResponseStatus()==200){
                return getSucceed(rw);
            } else {
                return getErr(ErrCode.ERROR_SYSTEM+"|"+rw.getResponseStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }

    /**
     * 功能：获取到聊天记录
     * 说明: 根据时间轴/分页条数
     */
    @RequestMapping(value = "/api/easemob/chatmsg", method = { RequestMethod.POST } )
    @ResponseBody
    public ResultModel testApiEasemobChatmsg(){
        SuperRecordModel SRModel = this.getSRModel();
        try {
            // [加号(+):%2B][大于(>):%3E][小于(<):%3C]
            // String qlSearch = "select%2B*%2Bwhere%2Btimestamp%3E1470471259227";
            ResponseWrapper rw = (ResponseWrapper) chat.exportChatMessages(999l,null,SRModel.getString("qlSearch"));
            if(rw.getResponseStatus()==200){
                String entities = ((ObjectNode) rw.getResponseBody()).get("entities").toString();
                // String cursor = ((ObjectNode) rw.getResponseBody()).get("cursor").asText();
                List<SuperRecordModel> list = SRModel.jsonToList(entities);
                for(SuperRecordModel srm:list){

                }
                return getSucceed(list);
            } else {
                return getErr(ErrCode.ERROR_SYSTEM + "|" + rw.getResponseStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return getErr(ErrCode.ERROR_SYSTEM);
        }
    }


}
